package org.simp.router;

import org.simp.common.Constants;
import org.simp.core.message.SimpMessage;
import org.simp.core.request.SimpRequest;
import org.simp.handler.SimpHandler;
import org.simp.node.SimpNode;
import org.simp.node.SimpServerAccepter;
/**
 * 自下而上的消息使用这个路由拦截器，将消息转发给上层服务器
 * @author zhuhaitao at 2014-5-28
 *
 */
public class ServerRouterInterceptor implements RouterInterceptor{

	@Override
	public boolean dispatchRequest(SimpRequest simpRequest, SimpHandler handler) {
		String contextName = handler.getContext().getContextName();
		String objAddress = simpRequest.getObjAddress();
		
		if(objAddress.endsWith(contextName) && objAddress.contains(Constants.ADDRESS_SPLIT)){
			dispatchSimpMessage(simpRequest.getSimpMessage(), handler);
			return true;
		}
		return false;
	}

	@Override
	public void dispatchSimpMessage(SimpMessage message, SimpHandler handler) {
		
		SimpNode node =  handler.getContext().getSimpNode();
		message.decObjAddress();
//		node.sendToUpNode(message);
		node.sendToDownNode(message);
		
	}

	protected boolean isCurrentAddress(String address,String contextName){
		
		String lastCurrentAddress = getLastAddress(address);
		return contextName.equals(lastCurrentAddress);
	}
	
	protected String getLastAddress(String address){
		if(address == null || "".equals(address)){
			return "";
		}
		String[] addresses = address.split(Constants.ADDRESS_SPLIT);
		return addresses[addresses.length -1];
	}
}
